package org.springframework.fusion.webscoket.config.websocket;

import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;

import org.springframework.fusion.webscoket.utlis.JsonUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

@Component
public class WebSocketMessageClass2 extends TextWebSocketHandler {
	
   private ConcurrentHashMap<String, WebSocketSession> sessionList = new ConcurrentHashMap<>();

	/**
	 * 接受消息
	 */
	@Override
	protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
		System.out.println("接受消息执行的方法" + JsonUtils.ObjectToJson(message.getPayload()));
		Object object = session.getAttributes().get("abc");
		System.out.println(object.toString());
		// 接收到客户端消息时调用
		super.handleTextMessage(session, message);
		session.sendMessage(new TextMessage(String.valueOf(new Date().getTime())));
	}

	/**
	 * 连接成功之后
	 */
	@Override
	public void afterConnectionEstablished(WebSocketSession session) throws Exception {
		sessionList.put(session.getId(), session);
		System.out.println("连接成功之后执行方法"+session.getId());
	}

	@Override
	public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
		System.out.println("出现异常之后执行方法");
	}

	/**
	 * 连接关闭之后
	 */
	@Override
	public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
		System.out.println("连接关闭之后执行方法");
		sessionList.remove(session.getId(), session);
	}

	public ConcurrentHashMap<String, WebSocketSession> getSessionList() {
		return sessionList;
	}
	
}